package meiyunting.shiwuzhaoling.config;

import meiyunting.shiwuzhaoling.model.User;
import meiyunting.shiwuzhaoling.model.UserRole;
import meiyunting.shiwuzhaoling.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Optional;

@Component
public class AdminInitializer implements CommandLineRunner {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    @Autowired
    public AdminInitializer(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public void run(String... args) {
        // 检查管理员账号是否存在
        Optional<User> adminUser = userRepository.findByUsername("admin");
        
        if (!adminUser.isPresent()) {
            System.out.println("创建默认管理员账号...");
            
            User admin = new User();
            admin.setUsername("admin");
            admin.setPassword(passwordEncoder.encode("admin123"));
            admin.setEmail("admin@example.com");
            admin.setRole(UserRole.ADMIN);
            admin.setCreatedAt(LocalDateTime.now());
            admin.setUpdatedAt(LocalDateTime.now());
            
            userRepository.save(admin);
            
            System.out.println("管理员账号创建成功！");
        } else {
            System.out.println("管理员账号已存在，无需创建。");
        }
    }
} 